package com.ctgu.computer.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@org.aspectj.lang.annotation.Aspect
@Component
public class Aspect {

    private static final String SET_CREATE_TIME = "setCreateTime";
    @Pointcut("@annotation(com.ctgu.computer.annotation.FillNowTime)")
    public void point(){}

    @Before("point()")
    public void autoFillLocalDateTimeNow(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("正在自动填充当前时间...");
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.now();
        String format = localDateTime.format(dateTimeFormatter);
        LocalDateTime now = LocalDateTime.parse(format,dateTimeFormatter);
        Object[] args = joinPoint.getArgs();
        Object arg = args[0];
        Method setCreateTime = arg.getClass().getDeclaredMethod(SET_CREATE_TIME, LocalDateTime.class);
        setCreateTime.invoke(arg,now);
    }
}
